package com.iemes.controller.work_plan;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.iemes.annotation.SystemLog;
import com.iemes.controller.index.BaseController;
import com.iemes.entity.CustomerRejectSfcInfoFormMap;
import com.iemes.entity.ProcessWorkFlowFormMap;
import com.iemes.entity.ShopOrderSfcFormMap;
import com.iemes.entity.ShoporderFormMap;
import com.iemes.exception.BusinessException;
import com.iemes.mapper.WorkPlan.ShoporderMapper;
import com.iemes.mapper.base.BaseMapper;
import com.iemes.service.CommonService;
import com.iemes.service.work_plan.CustomerRejectShoporderService;
import com.iemes.util.Common;
import com.iemes.util.DateUtils;
import com.iemes.util.ListUtils;
import com.iemes.util.ResponseHelp;
import com.iemes.util.ShiroSecurityHelper;
import com.iemes.util.UUIDUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 客退单控制器
 * @author Administrator
 *
 */
@RequestMapping("/work_plan/customer_reject_shoporder_maintenance/")
@Controller
public class CustomerRejectShoporderController extends BaseController{

	@Inject
	private BaseMapper baseMapper;
	
	@Inject
	private ShoporderMapper shoporderMapper;
	
	@Inject
	private CommonService commonService;
	
	@Inject
	private CustomerRejectShoporderService customerRejectShoporderService;
	
	private Logger log = Logger.getLogger(this.getClass());
	
	private static String REWORK = "rework";
	
	private String CustomerRejectShoporderUrl = Common.BACKGROUND_PATH + "/work_plan/customer_reject/customer_reject_shoporder_maintenance";
	
	/**
	 * 客退单首页
	 * @return
	 */
	@RequestMapping("customer_reject_shoporder_maintenance")
	public String CustomerRejectShoporderUrl(Model model, HttpServletRequest request) {
		handlePageRes(model, request);
		setSfcStatusList(model);
		return CustomerRejectShoporderUrl;
	}
	
	/**
	 * 保存客退单
	 * @return
	 */
	@ResponseBody
	@RequestMapping("saveCustomerRejectShoporder")
	@SystemLog(module = "客退单维护", methods = "客退单维护-保存客退单") // 凡需要处理业务逻辑的.都需要记录操作日志
	public String saveCustomerRejectShoporder(Model model, HttpServletRequest request) {
		try {
			ShoporderFormMap shoporderFormMap = getFormMap(ShoporderFormMap.class);
			String customerRejectSfcData = shoporderFormMap.getStr("customerRejectSfcData");
			JSONArray jsonArray = JSONArray.fromObject(customerRejectSfcData);
			List<CustomerRejectSfcInfoFormMap> list = new ArrayList<CustomerRejectSfcInfoFormMap>();
			
			String newShoporderId = UUIDUtils.getUUID();
			List<Map<String, Object>> listSfc = null;
			String mainItemId = "";
			
			
			//1、组装关联对象集合
			for (int i=0; i<jsonArray.size(); i++) {
				JSONObject jsonObject =(JSONObject)jsonArray.get(i);
				String oldSfc = ((JSONObject) jsonObject.get("old_sfc")).getString("value");
				String oldShoporderId = ((JSONObject) jsonObject.get("old_shoporder_id")).getString("value");
				String newSfc = ((JSONObject) jsonObject.get("new_sfc")).getString("value");
				
				//根据oldSfc查找主物料，确保每个oldSfc的主物料相同，否则提示出错
				if (i==0) {
					Map<String, String> param = new HashMap<String, String>();
					param.put("site_id", ShiroSecurityHelper.getSiteId());
					param.put("sfc", oldSfc);
					try {
						listSfc = shoporderMapper.getSfcByMainItemId(param);
						if (!ListUtils.isNotNull(listSfc)) {
							throw new BusinessException("未能检索到旧sfc【"+oldSfc+"】的相关信息，请确认后再试");
						}
					} catch (Exception e) {
						String msg = e.getMessage();
						log.error(msg);
						throw new BusinessException(msg);
					}
				}else {
					boolean rs = false;
					for (Map<String, Object> map : listSfc) {
						String sfc = map.get("sfc").toString();
						mainItemId = map.get("shoporder_item_id").toString();
						if (sfc.equals(oldSfc)) {
							rs = true;
						}
					}
					if (!rs) {
						throw new BusinessException("旧SFC"+oldSfc+"与列表前之前的旧SFC的主物料不相同。无法放置同一返工工单下进行生产，请确认后再试！！！");
					}
				}
				
				CustomerRejectSfcInfoFormMap customerRejectSfcInfoFormMap = new CustomerRejectSfcInfoFormMap();
				customerRejectSfcInfoFormMap.put("id", UUIDUtils.getUUID());
				customerRejectSfcInfoFormMap.put("old_sfc", oldSfc);
				customerRejectSfcInfoFormMap.put("new_sfc", newSfc);
				customerRejectSfcInfoFormMap.put("old_shoporder_id", oldShoporderId);
				customerRejectSfcInfoFormMap.put("new_shoporder_id", newShoporderId);
				customerRejectSfcInfoFormMap.put("site_id", ShiroSecurityHelper.getSiteId());
				customerRejectSfcInfoFormMap.put("create_user", ShiroSecurityHelper.getCurrentUsername());
				customerRejectSfcInfoFormMap.put("create_time", DateUtils.getStringDateTime());
				shoporderFormMap.put("shoporder_type", this.REWORK);
				list.add(customerRejectSfcInfoFormMap);
			}
			
			//2、组装客退工单信息
			
			shoporderFormMap.put("id", newShoporderId);
			shoporderFormMap.put("site_id", ShiroSecurityHelper.getSiteId());
			shoporderFormMap.put("shoporder_item_id", mainItemId);
			shoporderFormMap.put("shoporder_number", jsonArray.size());
			shoporderFormMap.put("shoporder_issued_number", 0);
			shoporderFormMap.put("status", 0);
			shoporderFormMap.put("is_sfc_auto_generate", -1);
			shoporderFormMap.put("create_user", ShiroSecurityHelper.getCurrentUsername());
			shoporderFormMap.put("create_time", DateUtils.getStringDateTime());
			
			customerRejectShoporderService.saveCustomerRejectShoporder(shoporderFormMap, list);
		}catch(Exception e) {
			String msg = e.getMessage();
			log.error(msg);
			return ResponseHelp.responseErrorText(msg);
		}
		return ResponseHelp.responseText();
	}
	
	/**
	 * 检索客退单
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("queryCustomerRejectShoporder")
	public String queryCustomerRejectShoporder(Model model, HttpServletRequest request) {
		try {
			String shoporderNo = request.getParameter("shoporder_no");
			
			handlePageRes(model, request);
			
			//	1、查询客退单信息
			ShoporderFormMap shoporderFormMap = new ShoporderFormMap();
			shoporderFormMap.put("shoporder_no", shoporderNo);
			shoporderFormMap.put("shoporder_type", "rework");
			shoporderFormMap.put("site_id", ShiroSecurityHelper.getSiteId());
			List<ShoporderFormMap> list = baseMapper.findByNames(shoporderFormMap);
			if (!ListUtils.isNotNull(list)) {
				throw new BusinessException("未检索到编号为："+shoporderNo+"的相关客退单信息");
			}
			ShoporderFormMap shoporderFormMap2 = list.get(0);
			model.addAttribute("shoporderFormMap", shoporderFormMap2);
			
			//	2、查客退单状态
			setSfcStatusList(model);
			
			// 3.查询工艺路线信息
			String processWorkflowId = shoporderFormMap2.getStr("process_workflow_id");
			queryProcessWorkflow(model, processWorkflowId);
			
			//查询关联信息
			CustomerRejectSfcInfoFormMap customerRejectSfcInfoFormMap = new CustomerRejectSfcInfoFormMap();
			customerRejectSfcInfoFormMap.put("new_shoporder_id", shoporderFormMap2.getStr("id"));
			customerRejectSfcInfoFormMap.put("site_id", ShiroSecurityHelper.getSiteId());
			List<CustomerRejectSfcInfoFormMap> listCustomerRejectSfcInfoFormMap = baseMapper.findByNames(customerRejectSfcInfoFormMap);
			if (ListUtils.isNotNull(listCustomerRejectSfcInfoFormMap)) {
				model.addAttribute("listCustomerRejectSfcInfoFormMap", listCustomerRejectSfcInfoFormMap);
			}
			
			model.addAttribute("successMessage", "检索成功");
		}catch(Exception e) {
			String msg = e.getMessage();
			log.error(msg);
			model.addAttribute("errorMessage", msg);
		}
		return CustomerRejectShoporderUrl;
	}
	
	/**
	 * 删除客退单
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("delCustomerRejectShoporder")
	public String delCustomerRejectShoporder(Model model, HttpServletRequest request) {
		try {
			handlePageRes(model, request);
			String shoporder_id = request.getParameter("shoporder_id");
			List<ShoporderFormMap> list = baseMapper.findByAttribute("id", shoporder_id, ShoporderFormMap.class);
			if (!ListUtils.isNotNull(list)) {
				throw new BusinessException("未检索到相关的工单信息，请确认信息是否无误！！！");
			}
			
			ShoporderFormMap shoporderFormMap = list.get(0);
			
			CustomerRejectSfcInfoFormMap customerRejectSfcInfoFormMap = new CustomerRejectSfcInfoFormMap();
			customerRejectSfcInfoFormMap.put("new_shoporder_id", shoporderFormMap.getStr("id"));
			customerRejectSfcInfoFormMap.put("site_id", ShiroSecurityHelper.getSiteId());
			List<CustomerRejectSfcInfoFormMap> list2 = baseMapper.findByNames(customerRejectSfcInfoFormMap);
			if (!ListUtils.isNotNull(list2)) {
				throw new BusinessException("未检索客退单："+shoporderFormMap.getStr("shoporder_no")+"下的相关SFC信息，请确认后再试！！");
			}
			customerRejectShoporderService.delCustomerRejectShoporder(shoporderFormMap, list2);
		}catch(Exception e) {
			String msg = e.getMessage();
			log.error(msg);
			model.addAttribute("errorMessage", msg);
			return CustomerRejectShoporderUrl;
		}
		model.addAttribute("successMessage", "删除成功");
		return CustomerRejectShoporderUrl;
	}
	
	/**
	 * 检验SFC信息
	 * @param model
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("checkSfcInfo")
	public String checkSfcInfo(Model model, HttpServletRequest request) {
		try {
			String sfc = request.getParameter("sfc");
			if (StringUtils.isEmpty(sfc)) {
				throw new BusinessException("旧SFC为空，请重新输入！！！");
			}
			
			ShopOrderSfcFormMap shopOrderSfcFormMap = new ShopOrderSfcFormMap();
			shopOrderSfcFormMap.put("site_id", ShiroSecurityHelper.getSiteId());
			shopOrderSfcFormMap.put("sfc", sfc);
			List<ShopOrderSfcFormMap> list = baseMapper.findByNames(shopOrderSfcFormMap);
			if (!ListUtils.isNotNull(list)) {
				throw new BusinessException("未能查询到旧SFC："+sfc+"的相关信息，请确认该SFC是否正确！！！");
			}
			ShopOrderSfcFormMap shopOrderSfcFormMap2 = list.get(0);
			String shoporder_id = shopOrderSfcFormMap2.getStr("shoporder_id");
			return ResponseHelp.responseText(shoporder_id);
		}catch(Exception e) {
			String msg = e.getMessage();
			log.error(msg);
			return ResponseHelp.responseErrorText(msg);
		}
	}
	
	private void setSfcStatusList(Model model) {
		Map<String, String> map = new HashMap<String, String>();
		int[] statusArray = new int[] { 0, 1, 2, 3, 4 };
		for (int status : statusArray) {
			map.put(String.valueOf(status), commonService.getSfcStatusStr(status));
		}
		model.addAttribute("sfcStatusList", map);
	}
	
	public void queryProcessWorkflow(Model model, String workflowId) {
		// 查工艺路线
		ProcessWorkFlowFormMap processWorkFlowFormMap = new ProcessWorkFlowFormMap();
		processWorkFlowFormMap.put("id", workflowId);
		List<ProcessWorkFlowFormMap> listProcessWorkFlowFormMap = baseMapper.findByNames(processWorkFlowFormMap);

		if (!ListUtils.isNotNull(listProcessWorkFlowFormMap)) {
			log.error("未检索到工单的工艺路线信息");
			model.addAttribute("errorMessage", "未检索到工单的工艺路线信息");
			return;
		}
		processWorkFlowFormMap = listProcessWorkFlowFormMap.get(0);
		model.addAttribute("processWorkFlowFormMap", processWorkFlowFormMap);
	}
}
